<template>
  <div class="move-track-main-content">
    <div ref="headPanel" style="width: 100%;height: 64px;">
      <HeadMenu :activePage="activePanel"/>
    </div>
    <div :style="contentStyle">
  <!-- 地图   -->
    <Mapframe ref="mapframe"
              :showMenuTools="showMenuTools"
              @mapInfoEvent="getMapInfo"
              @locateEvent="getLocate"
              @popupBtnClick="popupBtnClick"
              @afteGenMap="genMap"
              :device-data="devDatas"></Mapframe>
<!--    </div>-->
    <div id="queryToolId" class="query-tool" >
      <div class="in-box">
        <Row :gutter="12">
          <Col span="6">
            <DateTimeRangeSelect ref="eventTime" v-model="dateRange" :placeholder="$t('date')" width="100%"></DateTimeRangeSelect>
          </Col>
          <Col span="5">
            <Device5gModelSelect :cate=2 ref="srhDeviceSelect" width="100px" v-model="queryParam.where.deviceId"></Device5gModelSelect>
          </Col>
          <Col span="2">
            <Slider :title="$t('speed')" v-model="currentSpeed" :max="slider.max" :min="slider.min" style="margin-right: 5px" ></Slider>
          </Col>
          <Col span="11">
            <Button type="default" icon="ios-search" style="margin-right: 5px" @click="getData" :disabled="trackTool.animating">{{$t('search')}}</Button>
            <Button type="default" icon="ios-play" style="margin-right: 5px" @click="playTrack" :disabled="!trackTool.inited || trackTool.animating">{{$t('play')}}</Button>
            <Button type="default" icon="ios-square" @click="stop" :disabled="!trackTool.animating">{{$t('stop')}}</Button>
            <Button type="default" icon="ios-pause" style="margin-right: 5px" @click="pause" :disabled="!trackTool.animating">{{$t('pause')}}</Button>
          </Col>
        </Row>
      </div>
    </div>

    <!-- 右下文字提示   -->
    <div class="tag-div" >
      <div class="sth" :style="tagBoxStyle">
        <div style="margin-bottom: 5px;color: #0c0c0c">
          {{$t('current_location')}}：{{currentLocate}}
        </div>
        <div><span>{{currentMapInfo}}</span> </div>
      </div>
    </div>
    </div>

  </div>
</template>
<script>
import MainTopMenuPanel from "@/view/Home/component/MainTopMenuPanel";
import Mapframe from "@/view/Home/map/Mapframe";
import DateTimeRangeSelect from "_c/topnav/DateTimeRangeSelect"
import UserSelect from "_c/topnav/UserModelSelect";
import Orgselect from "_c/topnav/OrgSelect";
import Device5gModelSelect from "_c/topnav/Device5gModelSelect";
import DevicePosition from "@/api/DevicePosition";
import ol_geom_lineString from "ol/geom/LineString";
import ol_Feature from "ol/Feature";
import ol_geom_Point from "ol/geom/Point";
import {
  Circle as ol_style_Circle,
  Fill as ol_style_Fill,
  Stroke as ol_style_Stroke,
  Style as ol_style_Style
} from "ol/style";
import {Vector as ol_layer_Vector} from "ol/layer";
import ol_source_Vector from "ol/source/Vector";
import GPS from "@/view/Home/map/maptools/tool/Gps";
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import HeadMenu from "@/view/Home/component/HeadMenu";
import {apiResult} from "@/libs/util";


export default {
  /** 报错：Unknown custom element: <GbDevicetree> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
   *  把 GbDevicetree 改个名为 GbDevicetree1就可以了
   */

  name:"MoveTrackPlay",
  components: {Mapframe,DateTimeRangeSelect,UserSelect,Orgselect,Device5gModelSelect,HeadMenu},
  watch:{
    currentSpeed(val){
      if (this.trackTool.animating){
        this.trackTool.pause();
        this.trackTool.speed = val;
        this.trackTool.play();
      }else{
        this.trackTool.speed = val;
      }

    }
  },
  data(){
    return{
      api: new DevicePosition(),
      contentStyle:{width:'100%',height:'100%'},
      mapInfo:null,
      showMenuTools:false,
      activePanel:0,
      tagBoxStyle:{right:'5px',bottom: '5px'},
      devDatas:[],
      currentMapInfo:"《ArcGis image》，level：11",
      currentLocate:"112.34353, 22.343553",
      dateRange: [],
      queryParam: {
        page: {
          asc: ['time'],
          pages: 1,
          size: 2000,
          total: 0,
          current: 1,
        },
        where: {
          deviceId:null,
          beginTime:null,
          endTime:null
        },
        init:()=>{
          this.queryParam.where.deviceCode=null;
        }
      },
      deviceInfo:null,
      userInfo:null,
      trackData:[],
      slider: {
        min:1,
        max:50,
      },
      currentSpeed:10, //轨迹回放速度

      /**
       * 轨迹回放对象
       *
       */
      trackTool:{
        inited:false,
        animating:false,
        routeLength:0,
        routeCoords:[],
        styles:null,
        vectorLayer:null,
        now:null,
        speed:5,
        geoMarker:null,
        center:null,
/*        moveFeature:null,
        startAnimation:null,
        stopAnimation:null,
        pauseAnimation:null,
        clearVectorLayer:null,*/
        pauseIndex:0,//暂停位置，默认为0
        currentIndex:0,//当前位置

        init:(points)=>{
          // 轨迹
          //console.log("points>>> %o",points);
          const route = new ol_geom_lineString(points);
          this.trackTool.routeCoords = route.getCoordinates();
          this.trackTool.routeLength = this.trackTool.routeCoords.length;
          //移除原图层
          if (!!this.trackTool.vectorLayer){
            this.mapObj.removeLayer(this.trackTool.vectorLayer);
            this.trackTool.vectorLayer=null;
          }

          this.trackTool.animating = false;
          const that = this;
          // 轨迹线要素
          const routeFeature = new ol_Feature({
            type: 'route',
            geometry: route
          });
          // 轨迹点要素
          this.trackTool.geoMarker = new ol_Feature({
            type: 'geoMarker',
            geometry: new ol_geom_Point(this.trackTool.routeCoords[0])
          });

          // 创建样式
          this.trackTool.styles = {
            'route': new ol_style_Style({
              stroke: new ol_style_Stroke({
                width: 5,
                color: 'blue'
              })
            }),
            'geoMarker': new ol_style_Style({
              image: new ol_style_Circle({
                radius: 7,
                fill: new ol_style_Fill({color: 'red'}),
                stroke: new ol_style_Stroke({
                  color: 'green',
                  width: 3,
                }),
              }),
            })
          };
          // 创建要素图层
          this.trackTool.vectorLayer = new ol_layer_Vector({
            source: new ol_source_Vector({
              features: [
                routeFeature,
                that.trackTool.geoMarker
              ]
            }),
            style: function (feature) {
/*              if (!that.trackTool.animating && feature.get('type') === 'geoMarker') {
                return null;
              }*/
              return that.trackTool.styles[feature.get('type')];
            }
          });

          /**
           * 监听事件
           * Postcompose 事件触发
           */
          this.trackTool.moveFeature = function (event) {
            const frameState = event.frameState;
            if (that.trackTool.animating) {
              let elapsedTime = frameState.time - that.trackTool.now;
              that.trackTool.currentIndex = Math.round(that.trackTool.speed * elapsedTime / 1000);
              if (that.trackTool.pauseIndex >= 0){
                //是否暂停过
                that.trackTool.currentIndex = that.trackTool.pauseIndex+that.trackTool.currentIndex;
              }
              //console.log(that.trackTool.currentIndex);
              if (that.trackTool.currentIndex >= that.trackTool.routeLength) {
                that.trackTool.stopAnimation(true);
                return;
              }
              const currentPoint = new ol_geom_Point(that.trackTool.routeCoords[that.trackTool.currentIndex]);
              that.trackTool.geoMarker.setGeometry(currentPoint);
            }
            that.mapObj.render();
          };

          /**
           * 开始播放
           */
          this.trackTool.startAnimation=function (){
            if (that.trackTool.animating) {
              return;
            } else {
              if (that.trackTool.pauseIndex > 0){
                that.trackTool.animating = true;
                that.trackTool.now = new Date().getTime();
                that.mapObj.render();
              }else{
                that.trackTool.animating = true;
                that.trackTool.now = new Date().getTime();
                that.trackTool.geoMarker.setStyle(null);
                that.mapObj.on('postcompose', that.trackTool.moveFeature);
                that.mapObj.render();
              }
            }
          };

          // 停止动画
          this.trackTool.stopAnimation=function (ended) {
            that.trackTool.animating = false;
            that.trackTool.currentIndex=0;
            that.trackTool.pauseIndex=0;
            const coord = ended ? that.trackTool.routeCoords[that.trackTool.routeLength - 1] : that.trackTool.routeCoords[0];
            (that.trackTool.geoMarker.getGeometry()).setCoordinates(coord);
            that.mapObj.un('postcompose', that.trackTool.moveFeature);
          }

          //暂停
          this.trackTool.pauseAnimation=function () {
            that.trackTool.animating = false;
            that.trackTool.pauseIndex= that.trackTool.currentIndex;
          }

          this.trackTool.clearVectorLayer=function (){
            //console.log(">>>>>>>>>>> MoveTrackPlay.TrackTool.clear");
            if (!!that.trackTool.vectorLayer){
              that.mapObj.removeLayer(that.trackTool.vectorLayer);
              that.trackTool.vectorLayer=null;
            }
          }

          this.trackTool.inited =true;
          this.trackTool.center=points[0];
          this.mapObj.addLayer(this.trackTool.vectorLayer);
          if (this.mapObj.getView().getZoom() < 15){
            this.mapObj.getView().setZoom(15);
          }
          this.mapObj.getView().setCenter(this.trackTool.center);
        },

        play:()=>{
          this.trackTool.startAnimation();
        },
        pause:()=>{
          this.trackTool.pauseAnimation();
        },
        stop:()=>{
          this.trackTool.stopAnimation();
        },
        clear:()=>{
          //console.log("1");
          //console.log(this.trackTool.startAnimation());
          this.trackTool.clearVectorLayer();

        }
      }

    }
  },
  methods:{
    getMapInfo(event){
      //console.log(event);
      this.currentMapInfo=event;
    },
    getLocate(event){
      this.currentLocate=event;
    },
    initTrack(){
      //console.log(">>>>>>>>>>> MoveTrackPay.initTrack: trackData.length=",this.trackData.length);
      //console.log(">>>>>>>>>>> MoveTrackPay.initTrack: trackData= %o",this.trackData);
      if (!(!!this.trackData && this.trackData.length>0)){
        return;
      }
      let points = [];
      let latitude=null;
      let longitude=null;
      let centerPoint1=null;
      this.trackData.forEach(item=>{
        latitude=item.latitude;
        longitude=item.longitude;
        centerPoint1={lat:latitude,lon:longitude};
        if (this.mapInfo.coordinateType == 'GCJ02' && item.coordinateSystem == 'WGS84'){
          //谷歌高德
          centerPoint1 = new GPS().gps84ToGcj02(parseFloat(latitude), parseFloat(longitude));
        }else if (this.mapInfo.coordinateType == 'WGS84' && item.coordinateSystem == 'GCJ02') {
          //天地图
          centerPoint1 = new GPS().gcj02ToGps84(parseFloat(latitude), parseFloat(longitude));
        }else if (this.mapInfo.coordinateType == 'BD09' && item.coordinateSystem == 'WGS84') {
          //百度
          centerPoint1 = new GPS().gps84ToBd09(latitude, longitude);
        }//WGS84 和其它 不变
        points.push([centerPoint1.lon,centerPoint1.lat]);
      })
      this.trackTool.init(points);
    },
    playTrack(){
      this.trackTool.play();
    },
    pause(){
      this.trackTool.pause();
    },
    stop(){
      this.trackTool.stop();
    },
    genMap(map){
      this.mapObj=map;
    },
    clear(){
      this.trackTool.clear();
    },

    getData() {

      //console.log(this.dateRange);
      if (!(this.dateRange == null || this.dateRange.length < 2 || this.dateRange[0]=="")){
        this.queryParam.where.beginTime = this.dateRange[0];
        this.queryParam.where.endTime = this.dateRange[1];
      }
      if (this.trackTool.inited){
        this.clear();
      }
/*      console.log("***** MoveTrackPlay>>>range %o",this.dateRange)
      console.log("***** MoveTrackPlay>>>param %o",this.queryParam.where)*/

      /** 生成查询条件 */
      this.queryParam.page.current = 0;
      this.api.queryForTrackPlay(JSON.stringify(this.queryParam)).then(res => {
        this.tableData = null;
          apiResult(res.data,false,result=>{
            this.trackData = result.data.records;
            if (!this.trackData || this.trackData.length === 0){
              this.$Message.info("no data")
            }
            this.initTrack();
          });
      })
    },

    popupBtnClick(event,node, data){
      console.log("event: %o",event);
      console.log("node: %o",node);
      console.log("data: %o",data);
    },
    /**
     * 生成轨迹回放地图
     * @param data
     */
    genTrackMap(data){

    }
  },
  mounted() {
    this.mapInfo = new MapInfo().get();
    /** 为了显示用，调置默认值 */
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    end.setMilliseconds(999);
    this.dateRange=[start, end];
    //this.queryParam.where.deviceId=9;
    //this.$nextTick(() => {
    //  this.getData();
    //});
    this.activePanel=3;

    if (!!this.$refs.headPanel){
      this.contentStyle.height = document.body.clientHeight-this.$refs.headPanel.offsetHeight+"px";
    }
    const that = this;
    window.onresize = ()=>{
      if (!that.$refs.headPanel || !that.$refs.headPanel.offsetHeight){
        //console.log("no offsetHeight");
        return;
      }
      if (!!that.$refs.headPanel){
/*        console.log("true 1")
        if (!!that.$refs.headPanel.offsetHeight)
          console.log("true 2")*/
        that.contentStyle.height = document.body.clientHeight-that.$refs.headPanel.offsetHeight+"px";
        that.$nextTick(() => {
          that.$refs.mapframe.refreshMap();

        })

      }
    }

  }

}
</script>
<style lang="less">
  //@import "../../template";

  .move-track-main-content {
    width: 100%;
    height: 100%;
    background-color: #0c0c0c;
    display: flex;
    flex-direction: column;
    .div-head{
      position: absolute;
      top: 0;
      left: 0;
      overflow: hidden;
      z-index: 90;
      width: 100%;
      height: 64px;
    }

    /*.panel-count {
      margin-bottom: 10px;
      margin-top: 10px;
      .count-number {
        font-size: 30px;
        color: #ed4014;
      }
    }
    .panel-page {
      margin-top: 10px;
    }
    .panel-nav {
      margin-bottom: 10px;
      a {
        margin-right: 10px;
      }
    }*/
  }

  /* 底固文字提示 */
  .tag-div{
    .sth{
      font-size: .12rem;
      color: rgb(255, 255, 10);
      text-align: right;
      -webkit-transition: right .3s;
      transition: right .3s;
      position: absolute;
      bottom: 10px;
      right: 50px;
      z-index: 98;
    }
  }

  /*查询工具栏*/
  .query-tool{
    position: absolute;
    top: 73px;
    left: 10px;
    background-color: rgba(0, 0, 0, 0.50);
    height: 42px;
    right: 10px;
    border-bottom-right-radius: 5px;
    border-top-right-radius: 5px;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;

    -webkit-transition: left .1s;
    transition: left .1s;
    z-index: 100;
    .in-box{
      width: 100%;
      margin-top: 5px;
      margin-left: 10px;
      float: left;
    }
    .l{
      padding: 5px;
      background: #fff;
      border-radius: 3px;
    };
    .box-shadow {
      -webkit-box-shadow: 0 0 5px 0 rgba(0,0,0,0.24);
      box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.24);
    }
    .cursor-pointer{
      cursor: pointer;
    }
    .inline-block{
      display: inline-block;
    }
    .float-left {
      float: left;
    };
    .float-right {
      float: right;
    }
    .icondingwei {
      font-size: 14px;
      color: #0078ff;
      background: #fff;
    }
    .iconfont {
      font-family: iconfont!important;
      font-size: 14px;
      font-style: normal;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
    .r {
      height: 36px;
      padding: 10px;
      background: #fff;
      font-size: 12px;
      border-radius: 5px;
      font-family: SimSun;
      margin-left: 10px;
      .f-p{
        padding-left: 2px;
      }
      .f {
        border-right: 2px dotted #ccc;
        margin: 0 5px;
        padding-right: 7px;
      }
      .text {
        position: relative;
        top: -2px;
        margin: 0 3px;
        color: #333;
        line-height: 20px;
      }
    }
    .fullScreenBtn{
      width: 60px;
      height: 36px;
      line-height: 36px;
      margin-left: 10px;
      background-image: -webkit-gradient(linear,left top,right top,from(#0093f1),to(#1d78ed));
      background-image: linear-gradient(90deg,#0093f1,#1d78ed);
      border-radius: 6px;
      color: #fff;
      text-align: center;
      z-index: 100;
    }
  }
  /* 地图类型 */
  .sub-map-type{
    position: absolute;
    top: 130px;
    left: 0px;
    z-index: 98;
    .btn-panel {
      cursor: pointer;
      //width: 48px;
      border-bottom-right-radius: 5px;
      border-top-right-radius: 5px;
      /*background: #2d8cf0;*/
      background-color: rgb(5, 31, 112);
      transition: all 0s;
    }
    height: 48px;
    //width: 480px;
  }

  .sub-menu {
    position: absolute;
    top: 139px;
    left: 70px;
    z-index: 98;
    .warn-box {
      cursor: pointer;
      overflow: hidden;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      display: -webkit-box;
      display: -ms-flexbox;
      -ms-flex-align: center;
      color: hsla(0,0%,100%,.9);
      font-weight: 700;
      letter-spacing: 1px;
      font-size: 18px;
      display: inline-block;
    }
  }
</style>
